package com.the.ui.widge.photoview

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-11-03 16:56
 * @describe 缩放
 * @email 625805189@qq.com
 * @remark
 */
open class PhotoView6
@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : PhotoView5(context, attrs, defStyleAttr, defStyleRes) {

    private val scaleGestureDetector: ScaleGestureDetector by lazy {
        ScaleGestureDetector(context, PhotoScaleGestureListener())
    }

    /**
     * 是否为缩放操作
     */
    private var isScale: Boolean = false

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        //双指操作优先
        val result = scaleGestureDetector.onTouchEvent(event)
        if (!scaleGestureDetector.isInProgress) {
            return super.onTouchEvent(event)
        }
        return result
    }

    override fun getAnimator(): ObjectAnimator {
        return scaleAnimator.apply {
            if (isScale) {
                isScale = false;
                setFloatValues(smallScale, currentScale)
            } else {
                setFloatValues(smallScale, bigScale)
            }
        }
    }

    inner class PhotoScaleGestureListener : ScaleGestureDetector.OnScaleGestureListener {

        var initScale: Float = 0.0f

        override fun onScale(detector: ScaleGestureDetector?): Boolean {
            // 当前的缩放值不是最小且并没有进行双击放大
            val isScaleLarge = currentScale > smallScale && !isEnlarge
            // 当前的缩放值是最小且并进行了双击放大
            val isScaleSmall = currentScale == smallScale && isEnlarge
            // 这两种情况都要进行取反，双指放大的视为已经放大，双击时还原，双指缩小的视为最小，双击时放大
            if (isScaleLarge || isScaleSmall) {
                isEnlarge = !isEnlarge
            }
            currentScale = initScale * detector!!.scaleFactor
            isScale = true
            invalidate()
            return false
        }

        override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
            initScale = currentScale
            // 消费事件
            return true
        }

        override fun onScaleEnd(detector: ScaleGestureDetector?) {
            if (currentScale < smallScale) {
                isScale = true
                reverseAnimator()
            }
        }

    }

}